---
title: "Integrate Mastra in your SvelteKit project | Frameworks"
description: A step-by-step guide to integrating Mastra with SvelteKit.
---

import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import Steps from "@site/src/components/Steps";
import StepItem from "@site/src/components/StepItem";

# Integrate Mastra in your SvelteKit project

Mastra integrates with SvelteKit, making it easy to:

- Build flexible APIs to serve AI-powered features
- Simplify deployment with a unified codebase for frontend and backend
- Take advantage of SvelteKit's built-in [Actions](https://kit.svelte.dev/docs/form-actions) or [Server Endpoints](https://svelte.dev/docs/kit/routing#server) for efficient server-client workflows

Use this guide to scaffold and integrate Mastra with your SvelteKit project.

<Tabs>
  <TabItem value="actions" label="Actions">

  <Steps>

<StepItem>

Install Mastra

Install the required packages:

<Tabs>
  <TabItem value="npm" label="npm">
    ```bash copy
    npm install mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="yarn" label="yarn">
    ```bash copy
    yarn add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="pnpm" label="pnpm">
    ```bash copy
    pnpm add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="bun" label="bun">
    ```bash copy
    bun add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
</Tabs>

</StepItem>

<StepItem>

To integrate Mastra into your project, you have two options:

- Use the One-Liner

  Run the following command to quickly scaffold the default Weather agent with sensible defaults:

  ```bash copy
  npx mastra@beta init --default
  ```

  > See [mastra init](/reference/v1/cli/create-mastra) for more information.

- Use the Interactive CLI

  If you prefer to customize the setup, run the `init` command and choose from the options when prompted:

  ```bash copy
  npx mastra@beta init
  ```

Add the `dev` and `build` scripts to `package.json`:

```json title="package.json"
{
  "scripts": {
    ...
    "dev:mastra": "mastra dev",
    "build:mastra": "mastra build"
  }
}
```

</StepItem>

<StepItem>

Modify the `tsconfig.json` file in your project root:

```json title="tsconfig.json"
{
  ...
  "exclude": ["dist", ".mastra"]
}
```

</StepItem>

<StepItem>

The `VITE_` prefix is required for environment variables to be accessible in the Vite environment, that SvelteKit uses.
[Read more about Vite environment variables](https://vite.dev/guide/env-and-mode.html#env-variables).

```bash title=".env" copy
VITE_OPENAI_API_KEY=<your-api-key>
```

</StepItem>

<StepItem>

Add `.mastra` to your `.gitignore` file:

```bash title=".gitignore" copy
.mastra
```

</StepItem>

<StepItem>

Update the Mastra Agent

```typescript title="src/mastra/agents/weather-agent.ts"
import { createOpenAI } from "@ai-sdk/openai";

 const openai = createOpenAI({
   apiKey: import.meta.env?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY,
   compatibility: "strict"
 });
```

By reading env vars from both `import.meta.env` and `process.env`, we ensure that the API key is available in both the SvelteKit dev server and the Mastra Dev Server.

> More configuration details are available in the AI SDK docs. See [Provider Instance](https://ai-sdk.dev/providers/ai-sdk-providers/openai#provider-instance) for more information.

</StepItem>

<StepItem>

Start the Mastra Dev Server to expose your agents as REST endpoints:

<Tabs>
  <TabItem value="npm" label="npm">
    ```bash copy
    npm run dev:mastra
    ```
  </TabItem>
  <TabItem value="cli" label="CLI">
    ```bash copy
    mastra dev:mastra
    ```
  </TabItem>
</Tabs>

> Once running, your agents are available locally. See [Local Development Environment](/docs/v1/getting-started/studio) for more information.

</StepItem>

<StepItem>

With the Mastra Dev Server running, you can start your SvelteKit site in the usual way.

</StepItem>

<StepItem>

```bash copy
mkdir src/routes/test
```

</StepItem>

<StepItem>

Create a new Action, and add the example code:

```bash copy
touch src/routes/test/+page.server.ts
```

```typescript title="src/routes/test/+page.server.ts" showLineNumbers copy
import type { Actions } from "./$types";
import { mastra } from "../../mastra";

export const actions = {
  default: async (event) => {
    const city = (await event.request.formData()).get("city")!.toString();
    const agent = mastra.getAgent("weatherAgent");

    const result = await agent.generate(`What's the weather like in ${city}?`);
    return { result: result.text };
  },
} satisfies Actions;
```

</StepItem>

<StepItem>

Create a new Page file, and add the example code:

```bash copy
touch src/routes/test/+page.svelte
```

```typescript title="src/routes/test/+page.svelte" showLineNumbers copy
<script lang="ts">
	import type { PageProps} from './$types';
	let { form }: PageProps = $props();
</script>

<h1>Test</h1>

<form method="POST">
	<input name="city" placeholder="Enter city" required />
	<button type="submit">Get Weather</button>
</form>

{#if form?.result}
	<pre>{form.result}</pre>
{/if}

```

> You can now navigate to `/test` in your browser to try it out.

Submitting **London** as the city would return a result similar to:

```plaintext
The current weather in London is as follows:

- **Temperature:** 16°C (feels like 13.8°C)
- **Humidity:** 62%
- **Wind Speed:** 12.6 km/h
- **Wind Gusts:** 32.4 km/h
- **Conditions:** Overcast

If you need more details or information about a different location, feel free to ask!
```

</StepItem>

  </Steps>
</TabItem>

<TabItem value="server-endpoints" label="Server Endpoints">

  <Steps>

<StepItem>

Install the required packages:

<Tabs>
  <TabItem value="npm" label="npm">
    ```bash copy
    npm install mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="yarn" label="yarn">
    ```bash copy
    yarn add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="pnpm" label="pnpm">
    ```bash copy
    pnpm add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
  <TabItem value="bun" label="bun">
    ```bash copy
    bun add mastra@beta @mastra/core@beta @mastra/libsql@beta @ai-sdk/openai
    ```
  </TabItem>
</Tabs>

</StepItem>

<StepItem>

To integrate Mastra into your project, you have two options:

- Use the One-Liner

  Run the following command to quickly scaffold the default Weather agent with sensible defaults:

  ```bash copy
  npx mastra@beta init --default
  ```

  > See [mastra init](/reference/v1/cli/create-mastra) for more information.

- Use the Interactive CLI

  If you prefer to customize the setup, run the `init` command and choose from the options when prompted:

  ```bash copy
  npx mastra@beta init
  ```

Add the `dev` and `build` scripts to `package.json`:

```json title="package.json"
{
  "scripts": {
    ...
    "dev:mastra": "mastra dev",
    "build:mastra": "mastra build"
  }
}
```

</StepItem>

<StepItem>

Modify the `tsconfig.json` file in your project root:

```json title="tsconfig.json"
{
  ...
  "exclude": ["dist", ".mastra"]
}
```

</StepItem>

<StepItem>

The `VITE_` prefix is required for environment variables to be accessible in the Vite environment, that SvelteKit uses.
[Read more about Vite environment variables](https://vite.dev/guide/env-and-mode.html#env-variables).

```bash title=".env" copy
VITE_OPENAI_API_KEY=<your-api-key>
```

</StepItem>

<StepItem>

Add `.mastra` to your `.gitignore` file:

```bash title=".gitignore" copy
.mastra
```

</StepItem>

<StepItem>

Update the Mastra Agent

```typescript title="src/mastra/agents/weather-agent.ts"
import { createOpenAI } from "@ai-sdk/openai";

const openai = createOpenAI({
   apiKey: import.meta.env?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY,
   compatibility: "strict"
 });
```

By reading env vars from both `import.meta.env` and `process.env`, we ensure that the API key is available in both the SvelteKit dev server and the Mastra Dev Server.

> More configuration details are available in the AI SDK docs. See [Provider Instance](https://ai-sdk.dev/providers/ai-sdk-providers/openai#provider-instance) for more information.

</StepItem>

<StepItem>

Start the Mastra Dev Server to expose your agents as REST endpoints:

<Tabs>
  <TabItem value="npm" label="npm">
    ```bash copy
    npm run dev:mastra
    ```
  </TabItem>
  <TabItem value="cli" label="CLI">
    ```bash copy
    mastra dev:mastra
    ```
  </TabItem>
</Tabs>

> Once running, your agents are available locally. See [Local Development Environment](/docs/v1/getting-started/studio) for more information.

</StepItem>

<StepItem>

With the Mastra Dev Server running, you can start your SvelteKit site in the usual way.

</StepItem>

<StepItem>

```bash copy
mkdir src/routes/weather-api
```

</StepItem>

<StepItem>

Create a new Endpoint, and add the example code:

```bash copy
touch src/routes/weather-api/+server.ts
```

```typescript title="src/routes/weather-api/+server.ts" showLineNumbers copy
import { json } from "@sveltejs/kit";
import { mastra } from "../../mastra";

export async function POST({ request }) {
  const { city } = await request.json();

  const response = await mastra
    .getAgent("weatherAgent")
    .generate(`What's the weather like in ${city}?`);

  return json({ result: response.text });
}
```

</StepItem>

<StepItem>

Create a new Page, and add the example code:

```bash copy
touch src/routes/weather-api-test/+page.svelte
```

```typescript title="src/routes/weather-api-test/+page.svelte" showLineNumbers copy
<script lang="ts">
	let result = $state<string | null>(null);
	async function handleFormSubmit(event: Event) {
		event.preventDefault();
		const formData = new FormData(event.currentTarget);
		const city = formData.get('city')?.toString();
		if (city) {
			const response = await fetch('/weather-api', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ city })
			});
			const data = await response.json();
			result = data.result;
		}
	}
</script>

<h1>Test</h1>
<form method="POST" onsubmit={handleFormSubmit}>
	<input name="city" placeholder="Enter city" required />
	<button type="submit">Get Weather</button>
</form>

{#if result}
	<pre>{result}</pre>
{/if}
```

> You can now navigate to `/weather-api-test` in your browser to try it out.

Submitting **London** as the city would return a result similar to:

```plaintext
The current weather in London is as follows:

- **Temperature:** 16.1°C (feels like 14.2°C)
- **Humidity:** 64%
- **Wind Speed:** 11.9 km/h
- **Wind Gusts:** 30.6 km/h
- **Conditions:** Overcast

If you need more details or information about a different location, feel free to ask!
```

</StepItem>

  </Steps>
  </TabItem>
</Tabs>

## Next steps

- [Monorepo Deployment](/docs/v1/deployment/monorepo)
